import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { HttpRouterService } from '../../service/http-router.service';
import { HttpService } from '../../service/http.service';
import { StorageService } from '../../service/storage.service';
import * as _ from 'underscore';

@Component({
  selector: 'app-password',
  templateUrl: './password.component.html',
  styleUrls: ['./password.component.less']
})
export class PasswordComponent implements OnInit {

  public mobile = '';
  public captcha = '';
  public password = '';

  public getSms = true;
  public wait = 60;

  constructor(
    private _http: HttpService,
    private _router: Router,
    private _activatedRoute: ActivatedRoute,
    private _storage: StorageService,
    private _httpRouter: HttpRouterService
  ) { }

  ngOnInit() {
  }

  sendSms($event) {
    $event.stopPropagation();
    if (!this.mobile) {
      alert('请输入手机号！');
      return;
    }
    const param = 'mobile=' + this.mobile + '&event=zy_resetpwd';
    this._http.post(this._httpRouter.sendSms, param).then(res => {
      if (res.code === 1) {
        this.getSms = false;
        this.time();
        this._storage.setSessionObject('user', res.data);
      }

      alert(res.msg);
    });
  }

  time() {
    if (this.wait === 0) {
      this.getSms = true;
      this.wait = 60;
    }else {
      this.wait--;
      setTimeout(() => {
        this.time();
      }, 1000);
    }
  }

  resetPwd($event) {
    $event.preventDefault();
    const patrn = /^(\w){6,20}$/;
    if (!this.mobile) {
      alert('请输入手机号');
      return;
    }
    if (!this.captcha) {
      alert('请输入验证码');
      return;
    }
    if (!this.password) {
      alert('请设置密码');
      return;
    }
    if (!patrn.test(this.password)) {
      alert('请输入6-20位数字、字母或下划线');
      return;
    }

    const param = 'mobile=' + this.mobile
      + '&newpassword=' + this.password
      + '&captcha=' + this.captcha;

    this._http.post(this._httpRouter.resetpwd, param).then(res => {
      if (res.code === 1) {
        this._router.navigate(['/attache/login']);
      }else {
        alert(res.msg);
      }
    });
  }

}
